﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Collections;
using Microsoft.Office.Server.UserProfiles;
using System.Collections.Generic;
using System.Data;


namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class Clearance_Action_Print : LayoutsPageBase
    {

        decimal grdTotal = 0;
        public static string Accountablity;

        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string ClearanceRequestNo;
        public static string SourceLstName;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AccountablityLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;
        public static string lstGuid { get; set; }
        public string camlQry;
        public static string Mode;
        public static string TaskItemID;
        public static string submittedfor;
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList;
        public static string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string LeaveRefID;
        public static string refID;

        public static int ClearanceItemID;

        List<Users> wfUsers = new List<Users>();

        public static List<string> lstUsers = new List<string>();


        string[] buttonVisibilty = new string[5];

        private static SPListItemCollection oItemsColl = null;
        private static SPListItem oItems = null;

        public static string ClearanceType = null;

        public static bool CKClear = false;

        public static string DeptName;

        #endregion

        /// <summary>
        /// Class used to bind Approval users to generic list.
        /// It will used to check assign approval user for accountants on by one
        /// </summary>
        public class Users
        {
            public string user { get; set; }
        }

        public Clearance_Action_Print()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Clearance Forms";
            TaskLstName = "Clearance Tasks";
            CmntsLstName = "Clearance Comments";
            SourceLstName = "Leave Request Forms";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";
            AccountablityLstName = "User Clearance Accountablities";
        }

        /// <summary>
        /// Clearance Action form is submitted by directly or using Leave Request Dashboards
        /// Depends upon we get corresponding reference id or leave reference number.
        /// The Approval process starts from User department accountant, who check the accoutablity and submit the form.
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {

                if (!IsPostBack)
                {

                    Mode = Request.QueryString["Mode"];
                    refID = Request.QueryString["RefID"]; // From Dashboard.
                    LeaveRefID = Request.QueryString["LeaveRefID"]; // From Dashboard.
                    TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);

                    ClearanceType = null;
                    dtReqDate.SelectedDate = DateTime.Today;

                    if (Mode == "Print" || Mode == "View")
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            ReLoadDetails();
                            pnlAccMain.Visible = true; // To view the previous accounts accountablities
                            if (Mode == "View")
                                pplReqUser.Enabled = false;
                        });
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: HR Request form" + " :: " + "Parent" + " :: " + "Page_Load";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }


        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                if (refID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";
                if (LeaveRefID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";

                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {

                    lblClrReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtReqDate.SelectedDate = Convert.ToDateTime(lstDatas["RequestDate"]);

                    SetValuesToControls(lstDatas);
                    GetSetUserAccountablity();

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Clearance Action Form" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion


        private void SetValuesToControls(SPListItem lstDatas)
        {
            refID = Convert.ToString(lstDatas["Reference_x0020_Number"]);
            LeaveRefID = Convert.ToString(lstDatas["LeaveReferenceNo"]);

            ClearanceType = Convert.ToString(lstDatas["ClearanceType"]);
            lblClearanceType.Text = Convert.ToString(lstDatas["ClearanceType"]);


            if (ClearanceType.Contains("Vacation / (Annual)(Emergency)"))
            {
                trLeaves.Visible = true;
                LeaveRefID = Convert.ToString(lstDatas["LeaveReferenceNo"]);
                txtLeaveRefNo.Text = LeaveRefID;
                dtLeaveReqDate.Text = Convert.ToDateTime(lstDatas["LeaveRequestDate"]).ToString("dd/MM/yyyy");
            }
            else
            {
                trLeaves.Visible = false;
            }

            SetPickerEntry(pplReqUser, Convert.ToString(lstDatas["SubmittedFor"]));

            txtReqEmpId.Text = Convert.ToString(lstDatas["EmployeeID"]);
            txtReqDesignation.Text = Convert.ToString(lstDatas["Designation"]);
            txtReqDivision.Text = Convert.ToString(lstDatas["Division"]);
            txtReqDepartment.Text = Convert.ToString(lstDatas["Department"]);
            dtEffectiveon.Text = Convert.ToDateTime(lstDatas["EffectineOn"]).ToString("dd/MM/yyyy");
            submittedfor = Convert.ToString(lstDatas["SubmittedFor"]);
            SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, submittedfor);
            submittedfor = fldUser.LookupValue;

            ClearanceItemID = Convert.ToInt32(lstDatas["ID"]);

            if (SPContext.Current.Web.CurrentUser.LoginName.ToLower().Contains(pplReqUser.CommaSeparatedAccounts.ToLower()))
            {
                plnSettle.Visible = true;
            }
            else
            {
                plnSettle.Visible = false;
            }
            if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["OSSettlement"])))
            {
                pnlOSView.Visible = true;
                txtSettlement.Text = Convert.ToString(lstDatas["OSSettlement"]);
                if (txtSettlement.Text == "Guarantor")
                {
                    string guarantor = Convert.ToString(lstDatas["Guarantor"]);
                    SPFieldUserValue fldGrnr = new SPFieldUserValue(SPContext.Current.Web, guarantor);
                    txtSettlement.Text = txtSettlement.Text + " : " + fldGrnr.LookupValue;
                }
            }

            GetApprovedUsers(refID);
        }


        private void SetPickerEntry(PeopleEditor ppls, string SubmittedFor)
        {
            ArrayList _arrayList = new ArrayList();
            SPFieldUserValue fldUser = null;

            fldUser = new SPFieldUserValue(SPContext.Current.Web, SubmittedFor);
            txtReqUser.Text = fldUser.LookupValue;
            PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
            _pickerEntity.Key = fldUser.LookupValue;
            _pickerEntity.IsResolved = true;
            _arrayList.Add(_pickerEntity);
            ppls.UpdateEntities(_arrayList);
        }


        /// <summary>
        /// Add accountablity values to list or set accountablity values to gridview
        /// </summary>
        /// <returns></returns>
        private bool GetSetUserAccountablity()
        {
            bool ckUserInAccountablity = false;

            camlQry = "<Where><Or><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq><Eq>" +
                "<FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Or></Where><OrderBy>" +
                "<FieldRef Name=\"Created\" Ascending=\"False\" /></OrderBy>";
            oItemsColl = obj.GetSPListItems(SiteURL, AccountablityLstName, camlQry);
            if (oItemsColl != null)
            {
                gvAccountablity.DataSource = oItemsColl.GetDataTable();
                gvAccountablity.DataBind();
            }

            return ckUserInAccountablity;
        }

        protected void gvAccountablity_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                decimal rowTotal = Convert.ToDecimal
                            (DataBinder.Eval(e.Row.DataItem, "CashAdvance"));
                grdTotal = grdTotal + rowTotal;

            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                Label lbl = (Label)e.Row.FindControl("lblTotal");
                lbl.Text = grdTotal.ToString("c");
            }
        }


        private void GetApprovedUsers(string refNo)
        {
            SPListItemCollection oItemColl = null;
            string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
            oItemColl = obj.GetSPListItems(SiteURL, TaskLstName, camlQry);
            DataTable dt = new DataTable();
            // dt.Columns.Add("Approved By");
            DataRow dr;

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem oItem in oItemColl)
                        {
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                            dt.Columns.Add(oItem["ID"].ToString());
                        }

                        dr = dt.NewRow();
                        int wfCnt = dt.Columns.Count;
                        int i = 0;
                        foreach (SPListItem oItem in oItemColl)
                        {
                            if (i < wfCnt)
                            {
                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                if (Convert.ToString(fldUser.LookupValue).Contains("\\"))
                                {
                                    string user = Convert.ToString(fldUser.LookupValue);
                                    string[] users = user.Split('\\');
                                    int arrLenth = users.Length;
                                    if (arrLenth > 0)
                                        dr[i] = users[1];
                                    else
                                        dr[i] = users[0];
                                }
                                i++;
                            }
                        }
                        dt.Rows.Add(dr);
                        i = 0;
                        dr = dt.NewRow();
                        while (i < wfCnt)
                        {
                            dr[i] = "Approved By";
                            i++;
                        }
                        dt.Rows.Add(dr);
                        gvApprovers.DataSource = dt;
                        gvApprovers.DataBind();
                        gvApprovers.HeaderRow.Visible = false;
                    }

                }

            }

        }

    }
}